import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/singleton_manager.dart';

import '../entity/order_detail_entity.dart';
import '../entity/order_list_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';
import '../views/dialog_manager.dart';

///
/// 发表评价
///
class OrderPublishComment extends StatefulWidget {
  String sourceType = '';

  OrderPublishComment({Key? key, this.sourceType = '1'}) : super(key: key);

  @override
  State<OrderPublishComment> createState() => _OrderPublishCommentState();
}

class _OrderPublishCommentState extends State<OrderPublishComment> {
  var _content = '';
  double score = 5;

  OrderListData currentOrderListItem = OrderListData();
  OrderDetailEntity currentOrderDetail = OrderDetailEntity();

  @override
  void initState() {
    super.initState();
    if (widget.sourceType == "1") {
      currentOrderListItem = SingletonManager.instance.currentOrderListItem;
    }
    if (widget.sourceType == "2") {
      currentOrderDetail = SingletonManager.instance.currentOrderDetail;
    }
  }

  publishComment() async {
    if (_content.isEmpty) {
      EasyLoading.showToast("请填写评论内容");
      return;
    }

    // LogUtil.v(score);

    dynamic result = await Api.publishComment({
      "order_item_id": widget.sourceType == '1'
          ? currentOrderListItem.orderGoods[0].id
          : currentOrderDetail.data.goods[0].id,
      "level": score,
      "content": _content,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("发布成功");
      Routes.router.pop(context, {'result': 1});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: const Text('发表评价'),
          centerTitle: true,
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.symmetric(vertical: 30.w, horizontal: 30.w),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  decoration: BoxDecoration(
                    color: Config.colorWhite,
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  width: double.infinity,
                  padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 20.w),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CachedNetworkImage(
                            imageUrl: widget.sourceType == '1'
                                ? currentOrderListItem.store.logo
                                : currentOrderDetail.data.store.logo,
                            fit: BoxFit.fill,
                            width: 32.w,
                            height: 32.w,
                            errorWidget: (context, url, error) {
                              return Image.asset(
                                'assets/images/bg_default_400.png',
                                width: 32.w,
                                height: 32.w,
                                fit: BoxFit.fill,
                              );
                            },
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 10.w),
                          ),
                          Expanded(
                            child: Text(
                              widget.sourceType == '1'
                                  ? currentOrderListItem.store.name
                                  : currentOrderDetail.data.store.name,
                              style: TextStyle(fontSize: 24.sp),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(vertical: 20.w),
                        height: 140.w,
                        decoration: BoxDecoration(
                          border:
                              Border(bottom: BorderSide(color: Config.colorDivider, width: 1.w)),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 100.w,
                              height: 100.w,
                              margin: EdgeInsets.only(right: 20.w),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: CachedNetworkImage(
                                  imageUrl: widget.sourceType == '1'
                                      ? currentOrderListItem.orderGoods[0].skuSnap.imgPath
                                      : currentOrderDetail.data.goods[0].skuSnap.imgPath,
                                  fit: BoxFit.fill,
                                  width: 100.w,
                                  height: 100.w,
                                  errorWidget: (context, url, error) {
                                    return Image.asset(
                                      'assets/images/bg_default_400.png',
                                      width: 100.w,
                                      height: 100.w,
                                      fit: BoxFit.fill,
                                    );
                                  },
                                ),
                              ),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  width: 520.w,
                                  child: Text(
                                    widget.sourceType == '1'
                                        ? currentOrderListItem.orderGoods[0].skuSnap.goods.name
                                        : currentOrderDetail.data.goods[0].skuSnap.goods.name,
                                    softWrap: false,
                                    style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                                  ),
                                ),
                                Container(
                                  width: 520.w,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        widget.sourceType == '1'
                                            ? currentOrderListItem.orderGoods[0].skuSnap.specVal
                                                .toString()
                                            : currentOrderDetail.data.goods[0].skuSnap.specVal
                                                .toString(),
                                        softWrap: true,
                                        style:
                                            TextStyle(color: (Config.colorText1), fontSize: 20.w),
                                      ),
                                      Text(
                                        "X${widget.sourceType == '1' ? currentOrderListItem.orderGoods[0].buyNum : currentOrderDetail.data.goods[0].buyNum}",
                                        softWrap: true,
                                        style:
                                            TextStyle(color: (Config.colorText1), fontSize: 20.w),
                                      ),
                                    ],
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(top: 9.w),
                                ),
                                Text(
                                  widget.sourceType == '1'
                                      ? CommonUtils.formatAmountUnit(
                                          currentOrderListItem.money,
                                          currentOrderListItem.company,
                                          currentOrderListItem.money1,
                                          currentOrderListItem.company1)
                                      : CommonUtils.formatAmountUnit(
                                          currentOrderDetail.data.money,
                                          currentOrderDetail.data.company,
                                          currentOrderDetail.data.money1,
                                          currentOrderDetail.data.company1),
                                  softWrap: true,
                                  style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: Config.colorWhite,
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  width: double.infinity,
                  height: 300.w,
                  margin: EdgeInsets.only(top: 25.w),
                  padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 20.w, bottom: 20.w),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    textAlign: TextAlign.justify,
                    obscureText: false,
                    maxLength: 200,
                    maxLines: 10,
                    onChanged: (value) {
                      setState(() {
                        _content = value;
                      });
                    },
                    style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                    decoration: const InputDecoration(
                      hintStyle: TextStyle(color: Config.colorText3),
                      hintText: "说两句谈谈此次购物体验吧",
                      // counterText: '',
                      isDense: true,
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                    ),
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: Config.colorWhite,
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  width: double.infinity,
                  height: 120.w,
                  margin: EdgeInsets.only(top: 25.w),
                  padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 20.w, bottom: 20.w),
                  child: Row(
                    children: [
                      Text(
                        '商品评价',
                        style: TextStyle(color: Config.colorText1, fontSize: 26.sp),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 20.w),
                      ),
                      RatingBar.builder(
                        initialRating: 5,
                        minRating: 0.5,
                        direction: Axis.horizontal,
                        allowHalfRating: true,
                        itemCount: 5,
                        itemPadding: EdgeInsets.symmetric(horizontal: 5.w),
                        itemBuilder: (context, _) => Icon(
                          Icons.star_rounded,
                          color: Colors.redAccent,
                          size: 30.w,
                        ),
                        onRatingUpdate: (rating) {
                          // print(rating);
                          score = rating;
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 750.w,
                  height: 100.w,
                  padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                  margin: EdgeInsets.only(top: 45.w),
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {publishComment()},
                    style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    child: const Text('发布评价'),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
